package com.mv.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mv.mapper.AdminMapper;
import com.mv.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin login(Admin admin) {
        /*1.将密码加密处理*/
        String password = admin.getPassword();
        /*利用md5加密算法 进行加密*/
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_name", admin.getAdminName())
                .eq("password", md5Pass);
        Admin adminDB=adminMapper.selectOne(queryWrapper);
        if(adminDB == null){
            return null;
        }
        /*说明：用户和密码正确，返回秘钥*/
        String uuid = UUID.randomUUID().toString()
                .replace("-", "");
        adminDB.setToken(uuid).setLoginTime(new Date());
        return adminDB;
    }
    @Transactional
    @Override
    public Boolean logon(Admin admin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_name", admin.getAdminName());
        Admin adminDB = adminMapper.selectOne(queryWrapper);
        if(adminDB!=null){
            return false;
        }
        String password = admin.getPassword();
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        admin.setPassword(password).setJob("售票员");
        adminMapper.insert(admin);
        return true;
    }
}
